import React ,{useState ,useEffect} from 'react';
import style from './UserPassEdit.module.scss'
import {useNavigate} from "react-router-dom";
import {userPassEditApi ,userPassSureApi} from '../../http/userApi'
import md5 from 'js-md5'
import {notification} from "antd";

//定义弹窗失败提示的一些内容
const openNotification = (msg) => {
    notification.info({
        message: msg,
        description:
            '',
        placement:'top',
        duration: 1,
    });
};
function UserPassEdit(props) {
    const navigate = useNavigate()
    const initState = {
        oldPass:'',
        newPass:'',
        surepass:'',
    }
    const [state , setState] = useState(initState)
    const changeInput =(e)=>{
        setState({
            ...state,[e.target.name]:e.target.value
        })
    }
    //点击返回
    const backHandler =()=>{
        navigate(-1)
    }
    //点击提交
    const submitHandler =()=>{
        const userId = localStorage.getItem('userId');
        if(state.oldPass==''){
            return openNotification('请输入原密码')
        }
        if(state.newPass==''){
            return openNotification('请输入新密码')
        }
        if(state.surepass==''){
            return openNotification('请再次输入新密码')
        }
        if(state.surepass!=state.newPass){
            return openNotification('两次输入的密码不一致')
        }
        userPassSureApi({userId,password:md5(state.oldPass)})
            .then(res=>{
                if(res.data.code == 200 ){
                    userPassEditApi({userId,password:md5(state.surepass)})
                        .then(res=>{
                            console.log(res.data.code)
                            if(res.data.code==200){
                                backHandler()
                            }
                        })
                }else {
                    return openNotification('原密码错入，请重新输入')
                }
            })

    }

    return (
        <div>
            <div className={style.back} onClick={backHandler}>返回</div>
            <div className={style.header}>修改密码</div>
            <div className={style.item}>
                <div>原密码</div>
                <input type="password" value={state.oldPass} name="oldPass" onChange={(e)=>changeInput(e)}></input>
            </div>
            <div className={style.item}>
                <div>新密码</div>
                <input type="password"value={state.newPass} name="newPass" onChange={(e)=>changeInput(e)}></input>
            </div>
            <div className={style.item}>
                <div>再次输入新密码</div>
                <input type="password" value={state.surepass} name="surepass" onChange={(e)=>changeInput(e)}></input>
            </div>
            <div className={style.item}>
                <div></div>
                <div className={style.submit} onClick={submitHandler}>提交</div>
            </div>


        </div>
    );
}

export default UserPassEdit;